package edu.csu.smartpark.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.csu.smartpark.dao.UserDAO;
import edu.csu.smartpark.model.DO.UserDO;
import edu.csu.smartpark.model.PO.UserPO;
import edu.csu.smartpark.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;

/*
* @Description: 登录相关逻辑实现类
* @Author: LZY
* @Date: 2021/4/13 19:23
*/

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public UserDO getUserByPhone(String phone){
        QueryWrapper<UserPO> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        UserPO userPO = userDAO.selectOne(wrapper);
        if (userPO != null){
            UserDO userDO = new UserDO();
            BeanUtils.copyProperties(userPO, userDO);
            List<String> roles = Arrays.asList(userPO.getRoles().split(","));
            userDO.setRoles(roles);
            return userDO;
        }
        return null;
    }

    @Override
    public boolean isUsernameExist(String username){
        QueryWrapper<UserPO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username).select("username");
        Integer count = userDAO.selectCount(wrapper);
        return count > 0;
    }

    @Override
    public boolean isPhoneExist(String phone){
        QueryWrapper<UserPO> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone).select("phone");
        Integer count = userDAO.selectCount(wrapper);
        return count > 0;
    }

    public int register(UserDO userDO){
        UserPO userPO = new UserPO();
        BeanUtils.copyProperties(userDO, userPO);
        List<String> roles = userDO.getRoles();
        StringBuilder roleStr = new StringBuilder();
        for (int i = 0; i < roles.size(); i++){
            roleStr.append(roles.get(i));
            if (i != roles.size()-1)
                roleStr.append(",");
        }
        userPO.setRoles(roles.toString());
        int id = userDAO.insert(userPO);
        if(id > 0){
            // 注册成功
            return id;
        }
        return -1;
    }

}
